package org.smart4j.framework.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 反射工具类
 * @Description:
 * @Author: Administrator
 * @Date: 2017/8/14 0014 下午 9:00
 */
public final class ReflectionUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);

    /**
     * 创建实例
     * @param clazz
     * @return
     */
    public static Object mewInstance(Class<?> clazz) {
        Object instance;
        try {
            instance = clazz.newInstance();
        } catch (Exception e) {
            LOGGER.error("new instance failure",e);
            throw new RuntimeException(e);
        }
        return instance;
    }

    /**
     *  调用方法
     * @param object
     * @param method
     * @param args
     * @return
     */
    public static Object invokeMethod(Object object, Method method, Object... args) {
        Object result = null;
        try {
            result = method.invoke(object, args);
        } catch (Exception e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("invoke method  failure",e);
                throw new RuntimeException(e);
            }
        }
        return result;
    }

    /**
     * 设置属性
     * @param object
     * @param field
     * @param args
     * @return
     */
    public static Object setFiled(Object object, Field field, Object... args) {
        Object result = null;
        try {
            field.setAccessible(true);
            field.set(object, args);
        } catch (Exception e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("set field failure",e);
                throw new RuntimeException(e);
            }
        }
        return result;
    }
}
